// context.ts - 上下文信息收集工具
// @/utils/monitor/utils/context.ts

import { EventContext, DeviceInfo } from '../MonitorTypes';
import { getPlatform } from './platform';

/**
 * 获取事件上下文信息
 */
export function getEventContext(): EventContext {
  const context: EventContext = {
    timestamp: Date.now(),
    url: getCurrentUrl(),
    userAgent: getUserAgent(),
    deviceInfo: getDeviceInfo(),
    networkInfo: getNetworkInfo()
  };

  // #ifdef H5
  if (typeof window !== 'undefined') {
    // 视口信息
    if (typeof window.innerWidth !== 'undefined') {
      context.viewport = {
        width: window.innerWidth,
        height: window.innerHeight
      };
    }

    // 屏幕信息
    if (typeof screen !== 'undefined') {
      context.screen = {
        width: screen.width,
        height: screen.height,
        colorDepth: screen.colorDepth,
        pixelDepth: screen.pixelDepth
      };
    }

    // 页面信息
    if (typeof document !== 'undefined') {
      context.page = {
        title: document.title,
        referrer: document.referrer,
        visibilityState: document.visibilityState,
        readyState: document.readyState
      };
    }

    // 性能信息
    if (typeof performance !== 'undefined') {
      context.performance = {
        timeOrigin: performance.timeOrigin,
        now: performance.now()
      };
    }
  }
  // #endif

  // #ifdef MP
  if (typeof uni !== 'undefined') {
    try {
      const systemInfo = uni.getSystemInfoSync();
      context.miniProgram = {
        appName: systemInfo.appName || '',
        version: systemInfo.version || '',
        platform: systemInfo.platform || '',
        system: systemInfo.system || '',
        brand: systemInfo.brand || '',
        model: systemInfo.model || ''
      };

      // 小程序页面信息
      const pages = getCurrentPages();
      if (pages.length > 0) {
        const currentPage = pages[pages.length - 1];
        context.page = {
          route: currentPage.route,
          options: currentPage.options
        };
      }
    } catch (error) {
      if (typeof console !== 'undefined') {
        console.warn('[Context] Failed to get miniprogram context:', error);
      }
    }
  }
  // #endif

  return context;
}

/**
 * 获取设备信息
 */
export function getDeviceInfo(): DeviceInfo {
  const device: DeviceInfo = {
    platform: getPlatform(),
    language: getLanguage(),
    timezone: getTimezone(),
    cookieEnabled: getCookieEnabled(),
    onLine: getOnlineStatus()
  };

  // #ifdef H5
  if (typeof navigator !== 'undefined') {
    const ua = navigator.userAgent || '';
    
    device.userAgent = ua;
    device.vendor = navigator.vendor || '';
    device.hardwareConcurrency = navigator.hardwareConcurrency || 0;
    
    // @ts-ignore - 可能存在的属性
    device.deviceMemory = navigator.deviceMemory || 0;
    
    // 检测设备类型
    device.deviceType = getDeviceType(ua);
    
    // 检测操作系统
    device.os = getOperatingSystem(ua);
    
    // 检测浏览器
    device.browser = getBrowserInfo(ua);
  }
  // #endif

  // #ifdef MP
  if (typeof uni !== 'undefined') {
    try {
      const systemInfo = uni.getSystemInfoSync();
      device.platform = systemInfo.platform || '';
      device.os = systemInfo.system || '';
      device.osVersion = systemInfo.version || '';
      device.brand = systemInfo.brand || '';
      device.model = systemInfo.model || '';
      device.pixelRatio = systemInfo.pixelRatio || 1;
      device.screenWidth = systemInfo.screenWidth || 0;
      device.screenHeight = systemInfo.screenHeight || 0;
      device.windowWidth = systemInfo.windowWidth || 0;
      device.windowHeight = systemInfo.windowHeight || 0;
      device.statusBarHeight = systemInfo.statusBarHeight || 0;
      device.deviceType = 'miniprogram';
    } catch (error) {
      device.deviceType = 'miniprogram';
    }
  }
  // #endif

  return device;
}

/**
 * 获取网络信息
 */
export function getNetworkInfo(): any {
  const networkInfo: any = {};

  // #ifdef H5
  if (typeof navigator !== 'undefined') {
    // 在线状态
    networkInfo.onLine = navigator.onLine;

    // 网络连接信息
    const connection = (navigator as any).connection || 
                      (navigator as any).mozConnection || 
                      (navigator as any).webkitConnection;
    
    if (connection) {
      networkInfo.effectiveType = connection.effectiveType;
      networkInfo.downlink = connection.downlink;
      networkInfo.downlinkMax = connection.downlinkMax;
      networkInfo.rtt = connection.rtt;
      networkInfo.type = connection.type;
      networkInfo.saveData = connection.saveData;
    }
  }
  // #endif

  // #ifdef MP
  if (typeof uni !== 'undefined') {
    try {
      uni.getNetworkType({
        success: (res: any) => {
          networkInfo.networkType = res.networkType;
        }
      });
    } catch (error) {
      networkInfo.networkType = 'unknown';
    }
  }
  // #endif

  return networkInfo;
}

/**
 * 获取当前URL
 */
function getCurrentUrl(): string {
  // #ifdef H5
  if (typeof window !== 'undefined' && window.location) {
    return window.location.href;
  }
  // #endif

  // #ifdef MP
  if (typeof uni !== 'undefined') {
    const pages = getCurrentPages();
    if (pages.length > 0) {
      const currentPage = pages[pages.length - 1];
      return currentPage.route || 'unknown';
    }
  }
  // #endif

  return 'unknown';
}

/**
 * 获取用户代理
 */
function getUserAgent(): string {
  // #ifdef H5
  if (typeof navigator !== 'undefined') {
    return navigator.userAgent || '';
  }
  // #endif

  // #ifdef MP
  if (typeof uni !== 'undefined') {
    try {
      const systemInfo = uni.getSystemInfoSync();
      return `${systemInfo.platform} ${systemInfo.system} ${systemInfo.version}`;
    } catch (error) {
      return 'miniprogram';
    }
  }
  // #endif

  return 'unknown';
}

// getPlatform 函数已从 './platform' 模块导入

/**
 * 获取语言信息
 */
function getLanguage(): string {
  // #ifdef H5
  if (typeof navigator !== 'undefined') {
    return navigator.language || navigator.languages?.[0] || 'en';
  }
  // #endif

  // #ifdef MP
  if (typeof uni !== 'undefined') {
    try {
      const systemInfo = uni.getSystemInfoSync();
      return systemInfo.language || 'zh';
    } catch (error) {
      return 'zh';
    }
  }
  // #endif

  return 'en';
}

/**
 * 获取时区信息
 */
function getTimezone(): string {
  try {
    return Intl.DateTimeFormat().resolvedOptions().timeZone;
  } catch (error) {
    const offset = new Date().getTimezoneOffset();
    const hours = Math.abs(Math.floor(offset / 60));
    const minutes = Math.abs(offset % 60);
    const sign = offset > 0 ? '-' : '+';
    return `GMT${sign}${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
  }
}

/**
 * 获取Cookie启用状态
 */
function getCookieEnabled(): boolean {
  // #ifdef H5
  if (typeof navigator !== 'undefined') {
    return navigator.cookieEnabled;
  }
  // #endif

  return false;
}

/**
 * 获取在线状态
 */
function getOnlineStatus(): boolean {
  // #ifdef H5
  if (typeof navigator !== 'undefined') {
    return navigator.onLine;
  }
  // #endif

  return true; // 默认认为在线
}

/**
 * 检测设备类型
 */
function getDeviceType(userAgent: string): string {
  const ua = userAgent.toLowerCase();
  
  if (/mobile|android|iphone|ipod|blackberry|windows phone/i.test(ua)) {
    return 'mobile';
  } else if (/ipad|tablet/i.test(ua)) {
    return 'tablet';
  } else {
    return 'desktop';
  }
}

/**
 * 检测操作系统
 */
function getOperatingSystem(userAgent: string): string {
  const ua = userAgent.toLowerCase();
  
  if (/windows nt|win32|win64/i.test(ua)) {
    return 'Windows';
  } else if (/macintosh|mac os x/i.test(ua)) {
    return 'macOS';
  } else if (/linux/i.test(ua)) {
    return 'Linux';
  } else if (/android/i.test(ua)) {
    return 'Android';
  } else if (/ios|iphone|ipad|ipod/i.test(ua)) {
    return 'iOS';
  } else {
    return 'Unknown';
  }
}

/**
 * 检测浏览器信息
 */
function getBrowserInfo(userAgent: string): { name: string; version: string } {
  const ua = userAgent.toLowerCase();
  
  // Chrome
  if (/chrome/i.test(ua) && !/edge|edg/i.test(ua)) {
    const version = ua.match(/chrome\/(\d+\.\d+)/)?.[1] || '';
    return { name: 'Chrome', version };
  }
  
  // Edge
  if (/edge|edg/i.test(ua)) {
    const version = ua.match(/edge?\/(\d+\.\d+)/)?.[1] || '';
    return { name: 'Edge', version };
  }
  
  // Safari
  if (/safari/i.test(ua) && !/chrome/i.test(ua)) {
    const version = ua.match(/safari\/(\d+\.\d+)/)?.[1] || '';
    return { name: 'Safari', version };
  }
  
  // Firefox
  if (/firefox/i.test(ua)) {
    const version = ua.match(/firefox\/(\d+\.\d+)/)?.[1] || '';
    return { name: 'Firefox', version };
  }
  
  return { name: 'Unknown', version: '' };
}

/**
 * 获取内存信息
 */
export function getMemoryInfo(): any {
  // #ifdef H5
  if (typeof performance !== 'undefined' && (performance as any).memory) {
    const memory = (performance as any).memory;
    return {
      usedJSHeapSize: memory.usedJSHeapSize,
      totalJSHeapSize: memory.totalJSHeapSize,
      jsHeapSizeLimit: memory.jsHeapSizeLimit
    };
  }
  // #endif

  return null;
}

/**
 * 获取电池信息
 */
export async function getBatteryInfo(): Promise<any> {
  // #ifdef H5
  if (typeof navigator !== 'undefined' && (navigator as any).getBattery) {
    try {
      const battery = await (navigator as any).getBattery();
      return {
        charging: battery.charging,
        level: battery.level,
        chargingTime: battery.chargingTime,
        dischargingTime: battery.dischargingTime
      };
    } catch (error) {
      return null;
    }
  }
  // #endif

  return null;
}

/**
 * 获取简化的上下文信息（用于频繁调用）
 */
export function getLightContext(): Partial<EventContext> {
  return {
    timestamp: Date.now(),
    url: getCurrentUrl(),
    performance: typeof performance !== 'undefined' ? {
      now: performance.now(),
      timeOrigin: performance.timeOrigin
    } : undefined
  };
} 